/*
 * Copyrignt (c) qkier.com. All Rights Reserved.
 * Author: xuzeshui@qkier.com
 * Created Time: 2017-04-20 14:13:36
 * Last Modified: 2017-04-20 15:19:49
 * File Name: geo/bdlbs/geoconv.go
 * Description:
 */

//
package bdlbs

import (
	"fmt"
	"strconv"
	"strings"

	"doubimeizhi.com/jsonq"

	"github.com/astaxie/beego/httplib"
	log "github.com/cihub/seelog"
)

const (
	SERVICE_GEOCONV string = "http://api.map.baidu.com/geoconv/v1/"
)

//将输入坐标从from转成to对应的格式
func (p *BDLBSService) CoordConv(coords []*LocationItem, from int, to int) ([]*LocationItem, error) {
	if coords == nil || len(coords) == 0 {
		return make([]*LocationItem, 0, 0), nil
	}
	coordItem := make([]string, 0, len(coords))
	for _, li := range coords {
		coordItem = append(coordItem, fmt.Sprintf("%f,%f", li.Lng, li.Lat))
	}
	b := httplib.Get(SERVICE_GEOCONV)
	b.Param("ak", p.appkey)
	b.Param("output", "json")
	b.Param("from", strconv.Itoa(from))
	b.Param("to", strconv.Itoa(to))
	b.Param("coords", strings.Join(coordItem, ";"))
	data := make(map[string]interface{})
	if err := b.ToJSON(&data); err == nil {
		log.Debugf("data: %v", data)
		jq := jsonq.NewQuery(data)
		if status, err := jq.Int("status"); err == nil && status == 0 {
			if result, err := jq.ArrayOfObjects("result"); err == nil {
				coordRes := make([]*LocationItem, 0, len(result))
				for _, item := range result {
					lat := item["y"].(float64)
					lng := item["x"].(float64)
					coordRes = append(coordRes, &LocationItem{Lat: lat, Lng: lng})
				}
				return coordRes, nil
			} else {
				return nil, err
			}
		} else if err == nil {
			msg, _ := jq.String("message")
			return nil, fmt.Errorf("LBSE:%d:%s", status, msg)
		} else {
			return nil, err
		}
	} else {
		return nil, err
	}
}
